package Cantella::DJabberd::Web::InterfaceModel::Action::User::SetPassword;

use Reaction::Class;

#this is like the original but it asks you for your own password too

class SetPassword
  is 'Reaction::InterfaceModel::Action::User::SetPassword', which {

    has own_password => (isa => 'Password', is => 'rw', lazy_fail => 1);

    around error_for_attribute => sub {
        my $super = shift;
        my ($self, $attr) = @_;
        if ($attr->name eq 'own_password') {
            return "Password incorrect"
                unless $self->verify_own_password;
        }
        return $super->(@_); #commented out because the original didn't super()
    };

    around can_apply => sub {
        my $super = shift;
        my ($self) = @_;
        return 0 unless $self->verify_own_password;
        return $super->(@_);
    };

    implements verify_own_password => as {
        my $self = shift;
        return unless $self->has_own_password;

        #WTF, mate?
        #XXX hook into the auth plugin here
        my $user = $self->ctx->user->get_object;
        return $user->can("check_password") ?
          $user->check_password($self->own_password) :
                $self->own_password eq $user->password;
    };

    implements do_apply => as{
        my $self = shift;
        my $user = $self->target_model;
        $user->password($self->new_password);
        return $user;
    };
};

1;
